package service;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.DefaultTableModel;

import dao.StuDao;
import model.*;
public class StuService {
	StuDao stuDao = new StuDao();
	//查询全部学生
	public List <Student> findAllStu(){
		List <Student> stus = stuDao.findAll();
		return stus;
	}
	
	//根据id查询学生
	public List <Student> findStuById(int id){
		List <Student> stus = stuDao.findStuById(id);
		return stus;
	}
	
	//根据name查询学生
	public List <Student> findStuByName(String name){
		List <Student> stus = stuDao.findStuByName(name);
		return stus;
	}

	//添加学生
	public boolean insertStu (String id , String name , String age , String sex){
		try{
			Student stu = new Student(Integer.parseInt(id),name,Integer.parseInt(age),sex);
			return stuDao.insertStu(stu);
		}
		catch(NumberFormatException e){
			return false;
		}
	}
	
	//根据id删除学生
	public boolean deleteStuById(String id){
		try{
			int deleteId = Integer.parseInt(id);
			return stuDao.deleteStuById(deleteId);
		}catch(Exception e){
			return false;
		}
	}
	
	//根据文本框的内容进行查询，并显示到表格上
	public void searchAndShow(String input , DefaultTableModel tm){
		List <Student> stus = null;
		if(input.equals("")){
			stus = findAllStu();
		}
		else{
			try{
				int id = Integer.parseInt(input);
				stus = findStuById(id);
				if(stus.size() == 0){
					stus = findStuByName(input);
				}
					
			}
			catch(NumberFormatException e1){
				stus = findStuByName(input);
			}
		}
		tm.setRowCount(0);
		for(Student stu : stus){
			String [] row={stu.getId()+"",stu.getName(),stu.getAge()+"",stu.getSex()};
			tm.addRow(row);
		}
	}
	
	//修改学生
	public boolean updateStu (String id , String name , String age , String sex){
		try{
			Student stu = new Student(Integer.parseInt(id),name,Integer.parseInt(age),sex);
			return stuDao.updateStu(stu);
		}
		catch(NumberFormatException e){
			return false;
		}
	}
	
}
